package com.iflytek.flink;

import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

public class WordCountStream {
    public static void main(String[] args) throws Exception {
        //1、创建流处理环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //2、读取数据流：监控hadoop102的9999端口所发出的数据
        DataStreamSource<String> linetext = env.socketTextStream("hadoop121", 9999);
        //3、转换、分组、求和，得到统计结果
        SingleOutputStreamOperator<Tuple2<String, Long>> sum = linetext.flatMap((String line, Collector<Tuple2<String, Long>> out) -> {
            String[] words1 = line.split(" ");
            for (String word : words1) {
                out.collect(Tuple2.of(word, 1L));
            }
        }).returns(Types.TUPLE(Types.STRING, Types.LONG))
                .keyBy(data -> data.f0)
                .sum(1);
        sum.print();
        //4、执行环境
        env.execute();
    }
}
